package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {

    private static final long expire = 1000 * 60 * 60l;
    private static  SecretKey secretKey = Keys.hmacShaKeyFor("b8ad08a3a547e35829b821b75370301dd8c4b06bdd7771f9b541a75914068718".getBytes());
    /*
    * 创建token
    * token：包含头，负载，签名
    * 负载：用来保存登录用户的信息（userId，userName）
     */
    public static String createToken(String userName, Long userId) {

        String token = Jwts.builder()
                .setSubject("login-token") //token中的主题
                .setExpiration(new Date(System.currentTimeMillis() + expire)) //token过期时间
                .claim("userName", userName) //登录用户的账号
                .claim("userId", userId)  //登录用户的唯一标识id
                .signWith(secretKey) //签名
                .compressWith(CompressionCodecs.GZIP) //对token进行压缩，减少带宽的占用
                .compact(); //生成token

        return token;
    }

    //解析token
    public static Claims parseToken(String token) {
        Jws<Claims> claimsJws = null;
        try {
            claimsJws = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token);
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        return claimsJws.getBody();
    }
    public static void main(String[] args) {
        String token = createToken("admin", 1L);
        System.out.println(token);

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        Claims claims = parseToken(token);
        System.out.println(claims.get("userName"));
        System.out.println(claims.get("userId"));
        System.out.println(claims);
    }

}
